package com.eportal.service.impl;

import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.api.MdOpenApi;
import com.eportal.api.MdOpenBaseJson;
import com.eportal.base.BaseDAO;
import com.eportal.domain.AppStore;
import com.eportal.domain.CInstallUnit;
import com.eportal.domain.CRoom;
import com.eportal.domain.RoomUser;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TLock;
import com.eportal.domain.TUsers;
import com.eportal.domain.UsersApply;
import com.eportal.domain.UsersCommunity;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.exception.NotUniqueException;
import com.eportal.service.AppStoreService;
import com.eportal.service.CInstallUnitService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TKeysService;
import com.eportal.service.TLocksService;
import com.eportal.service.TUsersService;
import com.eportal.service.UsersCommunityService;
import com.eportal.service.UsersEnjoyService;
import com.eportal.util.DateUtils;
import com.eportal.util.MD5;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;

@Service("tUsersService")
public class TUsersServiceImpl  implements TUsersService{

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(TUsersServiceImpl.class.getName());

	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
    private AppStoreService appStoreService;
  /*  @Autowired
    private TCommunityService tCommunityService;*/
	@Autowired
	private TKeysService tKeysService;
	@Autowired
	private UsersCommunityService usersCommunityService;
	@Autowired
    private TLocksService tlocksService;
	@Autowired
    private CInstallUnitService cInstallUnitService;
	@Autowired
    UsersEnjoyService usersEnjoyService;

	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	@Override
	public TUsers get(Long sid){
		TUsers tUsers = (TUsers)dao.getById(TUsers.class, sid);
		return tUsers;
	}

	public TUsers getByWhere(String where){
		StringBuffer sb = new StringBuffer("from TUsers where ");
		sb.append(where);
		TUsers tUser = (TUsers) dao.loadObject(sb.toString());
		return tUser;
	}

	@Override
	public List<TUsers> list(JqGridPager jqGridPager) {
		 String sql = "select t.sid,t.userId,t.communityid,c.communityname,c.areacode,c.citycode,(cbu.cbname || cin.cbname||t2.room_no) as cbuname,u.agtcode,a.agtname,u.auname,u.nickName,u.tel,decode(t1.utype,'1','主业主','2','主租客','3','住户','4','租客') utype from T04_USERS_COMMUNITY t "
		 		+ "left join t035_room_user t1 on t1.app_userid = t.userid "
				+ "left join t035_room t2 on t1.room_id = t2.sid "
				+ "left join t04_users u on t.userid=u.userid "
		 		+ "left join t03_community c on t.communityid=c.sid "
		 		+ "left join t02_agtent a on a.agtcode=c.agtcode "
		 		+ "left join t032_cinstallunit cin on t.installunitId=cin.sid "
		 		+ "left join t031_cbuilding cbu on cin.cbuildingid=cbu.sid ";
	     return dao.query(sql, jqGridPager);
	}

	@Override
	public void delete(Long id) {
		TUsers tUsers = (TUsers) dao.getById(TUsers.class, id);
        dao.delete(tUsers);
	}

	@Override
	public void update(TUsers tUsers) throws Exception {
        dao.update(tUsers);
	}

	@Override
	public void delete(List<Long> ids) {
		 for (Long id : ids) {
	            delete(id);
	     }
	}
	@Override
	public TUsers add(TUsers tUsers) throws Exception {
		dao.save(tUsers);
        return tUsers;
	}

	/**
     * 住户新增保存
     */
    @LogAnnotation(operateDescribe="住户新增")
    public Map<String, Object> addMethod(TUsers tUser){
    	 String msg = ValidateUtil.validate(tUser);
         if (msg == null || msg.trim().length() == 0) {
             try {
            	 Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	 tUser.setPasswd(MD5.MD5Encode(tUser.getPasswd()));
            	 tUser.setcUserName(Long.toString(user.getSid()));
            	 tUser.setcTime(new Timestamp(System.currentTimeMillis()));
            	 add(tUser);
            	 result.put("objectId", tUser.getSid());
            	 result.put("code", 1);
                 result.put("msg", "操作成功");
             } catch (Exception e) {
                 log.error("住户保存失败", e);
                 result.put("code", 0);
                 result.put("msg", "操作失败");
             }
         } else {
             result.put("code", 0);
             result.put("msg", msg);
         }
         return result;
    }

	/**
     * 住户修改保存
     */
    @LogAnnotation(operateDescribe="住户修改")
    public Map<String, Object> updateMethod(TUsers tUser) {
    	 String msg = ValidateUtil.validate(tUser);
    	 result.put("objectId", tUser.getSid());
         if (msg == null || msg.trim().length() == 0) {
             try {
            	 TUsers entity = get(tUser.getSid());
             	if(StringUtils.isNotBlank(tUser.getAgtCode())){
             		entity.setAgtCode(tUser.getAgtCode());
             	}
             	if(StringUtils.isNotBlank(tUser.getAppId())){
             		entity.setAppId(tUser.getAppId());
             	}
             	if(StringUtils.isNotBlank(tUser.getTel())){
             		entity.setTel(tUser.getTel());
             	}
             	if(StringUtils.isNotBlank(tUser.getAuName())){
             		entity.setAuName(tUser.getAuName());
             	}
             	if(StringUtils.isNotBlank(tUser.getAuNo())){
             		entity.setAuNo(tUser.getAuNo());
             	}
             	if(StringUtils.isNotBlank(tUser.getAuCno())){
             		entity.setAuCno(tUser.getAuCno());
             	}
             	if(StringUtils.isNotBlank(tUser.getPasswd())){
            		entity.setPasswd(MD5.MD5Encode(tUser.getPasswd()));
            	}
             	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	 entity.setuUserName(Long.toString(user.getSid()));
            	 entity.setuTime(new Timestamp(System.currentTimeMillis()));
            	 update(entity);
                 result.put("code", 1);
                 result.put("msg", "操作成功");
             } catch (Exception e) {
                 log.error("住户更新失败", e);
                 result.put("code", 0);
                 result.put("msg", "操作失败");
             }
         } else {
             result.put("code", 0);
             result.put("msg", msg);
         }
         return result;
    }

	/**
     * 删除
     */
    @LogAnnotation(operateDescribe="住户删除")
    public Map<String, Object> deleteMethod(String param_ids){
    	 try {
    		 result.put("objectId", param_ids);
             for (String s : param_ids.split(",")) {
            	 UsersCommunity usersCommunity = usersCommunityService.get(Long.parseLong(s));
            	 usersCommunity.setStatus("3");
            	 usersCommunityService.update(usersCommunity);
            	 //钥匙失效
            	 invalidKeys(usersCommunity.getUserId(),usersCommunity.getCommunityId());
             }
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("住户删除失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
    	 return result;
    }
    /**
	 * 回收硬件后钥匙失效
	 * @param pid
     * @param string
	 */
	private void invalidKeys(String userId, String communityId) {
		try {
			StringBuffer sb =new StringBuffer("update T06_KEYS set status=1 where userId='");
			sb.append(userId);
			sb.append("' and communityId='");
			sb.append(communityId);
			sb.append("'");
			dao.updateBySql(sb.toString());
		} catch (Exception e) {
            log.error("钥匙置为失效失败，userId="+userId, e);
        }
	}

    /**
     * 住户审核
     */
	@Override
	@LogAnnotation(operateDescribe="住户审核")
	public Map<String, Object> auditMethod(String sid, String status,String roomStatus, String flag,String pubId, String prvId,String validityDate,String agtCode, String communityId)  throws Exception {
		 result.put("objectId", sid);
		 try {
			 UsersApply usersApply = getUsersApply(Long.parseLong(sid));
			 Sysopt  user= (Sysopt)getSession().getAttribute("user");
			 if ("-1".equals(user.getIsAdmin())) {
				 //TCommunity tCommunity =  tCommunityService.get(Long.parseLong(usersApply.getCommunityId()));
				 TCommunity tCommunity =  (TCommunity)dao.getById(TCommunity.class, Long.parseLong(usersApply.getCommunityId()));
				 usersApply.setOperateComm("平台超级管理员操作");
				 usersApply.setaUserName(tCommunity.getAdminUser());
			 }else{
				 usersApply.setaUserName(Long.toString(user.getSid()));
			 }
			 usersApply.setaTime(new Timestamp(System.currentTimeMillis()));
			 if("2".equals(status)){//拒绝
				 usersApply.setStatus(status);
				 updateUsersApply(usersApply);
				 result.put("code", 1);
		         result.put("msg", "操作成功");
		         return result;
			 }

			TUsers tUser = getFromUsersApply(usersApply);
			if (tUser == null) {
				 result.put("code", 0);
	             result.put("msg", "查询用户为空,用户未注册");
	             return result;
			}
			changeUser(tUser,usersApply.getAuName());

	        //是否更新用户社区关系表
			result = updateUsersCommunity(usersApply.getCommunityId(),usersApply.getInstallUnitId(),tUser.getUserId());
			if ("0".equals(result.get("code").toString())) {
				return result;
			}
			//增加房间住户表数据
			result = addRoomUser(tUser, usersApply, roomStatus);
			if ("0".equals(result.get("code").toString())) {
				return result;
			}
			//更新房间状态
			if(usersApply.getRoomId()!=null){//老版本app申请时，不填写房间，不填写房间的不用更新房间状态
				result = updateRoom(usersApply.getRoomId(), roomStatus);
				if ("0".equals(result.get("code").toString())) {
					return result;
				}
			}
			//门禁查询
			if("1".equals(flag)){//如果选择默认，则默认分配改社区所有的公共门禁和该用户所在单元的门禁
		         StringBuilder querypubLock = new StringBuilder();
		         querypubLock.append("select t.sid from t05_locks t where t.status='1' and t.ispubunit='1' and t.communityid='");
		         querypubLock.append(communityId);
		         querypubLock.append("'");
		         pubId = getLockBySql(querypubLock.toString());

		         StringBuilder queryprvLock = new StringBuilder();
		         queryprvLock.append("select t.sid from t05_locks t where t.status='1' and t.ispubunit='0' and t.communityid='");
		         queryprvLock.append(communityId);
		         queryprvLock.append("' and t.installunitid='");
		         queryprvLock.append(String.valueOf(usersApply.getInstallUnitId()));
		         queryprvLock.append("'");
		         prvId = getLockBySql(queryprvLock.toString());
			}
			result = lockList(pubId,prvId);
			if ("0".equals(result.get("code").toString())) {
				return result;
			}
			List<TLock> list = (List<TLock>) result.get("lockList");
			result = tKeysService.SyncTo(tUser,list,validityDate,agtCode,null);
			if ("1".equals(result.get("code").toString())) {
				usersApply.setStatus(status);
				updateUsersApply(usersApply);
			}
			try {
				MdOpenBaseJson json = MdOpenApi.sendMsg(tUser.getUserId(),null,"user","key_1");
    		} catch (Exception e) {
    			 log.error("推送消息失败",e);
    		}
         } catch (Exception e) {
             log.error("钥匙发放失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
             throw new MdKnownRunTimeException("钥匙发放失败");
         }
		 return result;
	}

	//更新房间状态
	private Map<String, Object> updateRoom(String roomId, String roomStatus){
		try{
		result = new HashMap<String, Object>();
		CRoom cRoom = (CRoom) dao.getById(CRoom.class, Long.valueOf(roomId));
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t035_room_user t where t.room_id = '");
		sb.append(roomId);
		sb.append("' and t.utype = '4'");
		List<Map<String, Object>> list =  dao.queryBySql(sb.toString());
		if(list.size()>0){
			cRoom.setStatus("2");
		}else{
			cRoom.setStatus(roomStatus);
		}
		}catch(Exception e){
			result.put("code", 0);
			result.put("msg", "更新房间状态失败");
			return result;
		}
		result.put("code", 1);
		result.put("msg", "更新房间状态成功");
		return result;
	}
	//住户审核增加房间住户表数据
	private Map<String, Object> addRoomUser(TUsers tUser,UsersApply usersApply,String roomStatus){
		result = new HashMap<String, Object>();
		String utype = "";
		if("2".equals(roomStatus)){
			utype = "4";
		}else{
			utype="3";
		}
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t035_room_user t where t.app_userid = '");
		sb.append(tUser.getUserId());
		sb.append("' and t.room_id = '");
		sb.append(usersApply.getRoomId());
		sb.append("' and t.utype='");
		sb.append(utype);
		sb.append("'");
		List<Map<String, Object>> list =  dao.queryBySql(sb.toString());
		if(list.size()==0){
			RoomUser roomUser = new RoomUser();
			roomUser.setCTime(new Timestamp(System.currentTimeMillis()));
			roomUser.setUserId(tUser.getUserId());
			roomUser.setRoomId(usersApply.getRoomId());
			roomUser.setUserType(utype);
			roomUser.setTel(tUser.getTel());
			roomUser.setUserName(tUser.getAuName());
			try {
				dao.save(roomUser);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				log.error("住户添加失败", e);
				result.put("code", 0);
				result.put("msg", "住户添加失败");
				return result;
			}
		}
		result.put("code", 1);
		result.put("msg", "住户添加成功");
		return result;
	}
	private String getLockBySql(String sql){
		String lockList = "";
		ArrayList<String> arr = new ArrayList<>();
		List<Map<String, Object>> list = dao.queryBySql(sql);
        for(Map<String, Object> map: list){
        	arr.add(map.get("sid").toString());
        }
        lockList = StringUtils.join(arr, ",");
		return lockList;
	}

	private void changeUser(TUsers tUser, String auName) {
		try {
			Boolean ifchange = false;
			if(StringUtils.isBlank(tUser.getAuName())){
				tUser.setAuName(auName);
				ifchange = true;
			}
			if(StringUtils.isBlank(tUser.getNickName())){
				tUser.setNickName(tUser.getTel().substring(tUser.getTel().length()-4,tUser.getTel().length()));
				ifchange = true;
			}
			if (ifchange) {
				update(tUser);
			}
		} catch (Exception e) {
			 log.error("用户姓名和昵称更新失败", e);
		}
	}

	public Map<String, Object> updateUsersCommunity(String communityId,Long installUnitId, String userId) {
		try {
			StringBuffer sb = new StringBuffer(" communityId ='");
			sb.append(communityId);
			sb.append("'");
			sb.append(" and userId='");
			sb.append(userId);
			sb.append("'");
			UsersCommunity usersCommunity = usersCommunityService.getByWhere(sb.toString());
			if (usersCommunity == null) {
				UsersCommunity usersCommun =  new UsersCommunity();
				if (installUnitId != 0L) {
					CInstallUnit cInstallUnit = cInstallUnitService.get(installUnitId);
					usersCommun.setCbuildingId(cInstallUnit.getcBuildingId());
					usersCommun.setInstallunitId(Long.toString(installUnitId));
				}
				usersCommun.setCommunityId(communityId);
				usersCommun.setUserId(userId);
				usersCommun.setScore(0L);
				usersCommun.setBadges(0L);
				usersCommun.setEnjoyOrder(0L);
				usersCommun.setStatus("1");
				usersCommun.setEnjoyStatus("1");
				usersCommun.setAlbumStatus("1");
				usersCommun.setcTime(new Timestamp(System.currentTimeMillis()));
				usersCommunityService.add(usersCommun);
			}else if("3".equals(usersCommunity.getStatus())){//禁用状态
				 usersCommunity.setStatus("1");
            	 usersCommunityService.update(usersCommunity);
			}

			result.put("code", 1);
			result.put("msg", "操作成功");
		} catch (Exception e) {
			log.error(this, e);
			 result.put("code", 0);
             result.put("msg", "操作失败");
             throw new MdKnownRunTimeException("用户社区表更新失败");
		}
		return result;
	}

	private Map<String, Object> lockList(String pubId,String prvId) {
		 List<String> listRids = new LinkedList<String>();
	        if (StringUtils.isNotBlank(pubId)) {
	    		String[] arr = pubId.split(",");
	    		List<String> listArr = Arrays.asList(arr);
	    		listRids.removeAll(listArr);
	    		listRids.addAll(listArr);
	    	}
	        if (StringUtils.isNotBlank(prvId)) {
	    		String[] arr = prvId.split(",");
	    		List<String> listArr = Arrays.asList(arr);
	    		listRids.removeAll(listArr);
	    		listRids.addAll(listArr);
	    	}
	    	final List<Long> rids = new LinkedList<Long>();
	    	for (String str : listRids) {
				rids.add(Long.parseLong(str));
			}
			if (rids == null) {
				 result.put("code", 0);
	             result.put("msg", "发放钥匙为空！");
	             return result;
			}
			//查询pid
			 //获取角色中的菜单id集合
	        String sql = "from TLock where sid in (:ids)";
	        List<TLock> list = dao.executeFind(sql,"ids",rids);
	        if (list.size() <1) {
	        	 result.put("code", 0);
	             result.put("msg", "查询门禁为空");
	             return result;
			}
	      //调用接口
//	        String pid = "";
//
//			for (int i = 0; i < list.size(); i++) {
//				if (pid != "") {
//					pid +=",";
//				}
//				pid +=list.get(i).getPid();
//				result.put(list.get(i).getPid(), list.get(i).getInstallunitId());
//			}
	        result.put("code", 1);
	        result.put("msg", "操作成功");
	        result.put("lockList", list);
	        result.put("communityId", list.get(0).getCommunityId());
		return result;
	}


	private TUsers getFromUsersApply(UsersApply usersApply) {
		StringBuffer sb = new StringBuffer("from TUsers where ");
//		sb.append(usersApply.getCommunityId());
//		sb.append("'");
		sb.append(" appId ='");
		sb.append(usersApply.getAppId());
		sb.append("'");
		sb.append("  and tel ='");
		sb.append(usersApply.getTel());
		sb.append("'");
		return (TUsers) dao.loadObject(sb.toString());
	}



	@Override
	public List<Map<String, String>> getApplyDetail(String sid) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append("select t1.auname,t1.tel,t1.comm,to_char(t1.ctime,'yyyy-MM-dd HH24:mi:ss')as ctime,t3.cbname||t2.cbname||t4.room_no room ");
		sb.append("from T04_USERS_APPLY t1,t032_cinstallunit t2,t031_cbuilding t3,t035_room t4 ");
		sb.append("where t1.installunitid = t2.sid (+) ");
		sb.append("and t2.cbuildingid = t3.sid(+)" );
		sb.append("and t1.room_id = t4.sid(+) ");
		sb.append("and t1.sid = '");
		sb.append(sid);
		sb.append("'");
		return dao.queryBySql(sb.toString());
	}

	@Override
	public List<UsersApply> userApplyList(JqGridPager jqGridPager,String agtCode, String communityId) {
		int userRole =  (Integer) getSession().getAttribute("userRole");
		StringBuffer sb  = new StringBuffer();
		sb.append("select * from (");
		if (userRole == 1) {
			sb.append("select a.sid,ag.agtname,cm.communityname,a.comm,a.agtcode,a.communityid,a.tel,a.roomno,a.auname,a.attachfile,a.status,'('||a.operatecomm||')'||s.uname as ausername,to_char(a.atime,'yyyy-MM-dd HH24:mi:ss')as atime,to_char(a.ctime,'yyyy-MM-dd HH24:mi:ss')as ctime,c.cbname||b.cbname||a.Roomno as installunitid ");
		}else{
			sb.append("select a.sid,ag.agtname,cm.communityname,a.comm,a.agtcode,a.communityid,a.tel,a.roomno,a.auname,a.attachfile,a.status,s.uname as ausername,to_char(a.atime,'yyyy-MM-dd HH24:mi:ss')as atime,to_char(a.ctime,'yyyy-MM-dd HH24:mi:ss')as ctime,c.cbname||b.cbname||a.Roomno as installunitid ");
		}
		sb.append(" from T04_USERS_APPLY a "
		 		+ " left join t02_agtent ag on ag.agtcode=a.agtcode"
		 		+ " left join t03_community cm on cm.sid=a.communityid"
		 		+ " left join t032_cinstallunit b on a.installunitid=b.sid"
		 		+ " left join t031_cbuilding c on b.cbuildingid= c.sid"
		 		+ " left join sysopt s on a.ausername=s.sid ");
		sb.append(" where a.agtCode = '");
		sb.append(agtCode);
		sb.append("' and a.communityId = '");
		sb.append(communityId);
		sb.append("' and a.status='0' order by a.ctime desc)");
		sb.append(" union all ");
		sb.append("select * from (");
		if (userRole == 1) {
			sb.append("select a.sid,ag.agtname,cm.communityname,a.comm,a.agtcode,a.communityid,a.tel,a.roomno,a.auname,a.attachfile,a.status,'('||a.operatecomm||')'||s.uname as ausername,to_char(a.atime,'yyyy-MM-dd HH24:mi:ss')as atime,to_char(a.ctime,'yyyy-MM-dd HH24:mi:ss')as ctime,c.cbname||b.cbname||a.Roomno as installunitid ");
		}else{
			sb.append("select a.sid,ag.agtname,cm.communityname,a.comm,a.agtcode,a.communityid,a.tel,a.roomno,a.auname,a.attachfile,a.status,s.uname as ausername,to_char(a.atime,'yyyy-MM-dd HH24:mi:ss')as atime,to_char(a.ctime,'yyyy-MM-dd HH24:mi:ss')as ctime,c.cbname||b.cbname||a.Roomno as installunitid ");
		}
		sb.append(" from T04_USERS_APPLY a "
		 		+ " left join t02_agtent ag on ag.agtcode=a.agtcode"
		 		+ " left join t03_community cm on cm.sid=a.communityid"
		 		+ " left join t032_cinstallunit b on a.installunitid=b.sid"
		 		+ " left join t031_cbuilding c on b.cbuildingid= c.sid"
		 		+ " left join sysopt s on a.ausername=s.sid ");
		sb.append(" where a.agtCode = '");
		sb.append(agtCode);
		sb.append("' and a.communityId = '");
		sb.append(communityId);
		sb.append("' and (a.status='1' or a.status='2') order by a.aTime desc)");
	     return dao.query(sb.toString(), jqGridPager);
	}

	@Override
	public UsersApply getUsersApply(Long sid) {
		UsersApply usersApply = (UsersApply)dao.getById(UsersApply.class, sid);
		return usersApply;
	}

	@Override
	public void updateUsersApply(UsersApply usersApply) throws Exception {
		dao.update(usersApply);

	}

	/**
	 * 预发钥匙
	 * @param appId
	 */
	@Override

	public Map<String, Object> authorizeKeysMethod(String data, String pubId, String prvId, Date validityDate,String communityId, String agtCode, String appId,Date startTime) {
		try {
			//保存用户
			if (StringUtils.isBlank(data)) {
				 result.put("code", 0);
	             result.put("msg", "所选人员为空！");
	             return result;
			}
			String[] users = data.split(",");
			TUsers tuser;
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			//TCommunity tCommunity = tCommunityService.get(Long.parseLong(communityId));
			TCommunity tCommunity = (TCommunity)dao.getById(TCommunity.class,Long.parseLong(communityId));
			List<TUsers> tUsers = new ArrayList<TUsers>();
			Boolean bool = true;
			for(int i = 0; i < users.length; i++){
				String[] detail = users[i].split(";");
				String regex = "^1[3|4|5|7|8]\\d{9}$";
				if(!Pattern.matches(regex, detail[0])){
					bool = false;
				}
			}
			if(!bool){
				 result.put("code", 0);
	             result.put("msg", "预发用户中手机号格式不正确");
	             return result;
			}
			for (int i = 0; i < users.length; i++) {
				String[] detail = users[i].split(";");
				StringBuffer where  = new StringBuffer();
				where.append(" tel= '");
				where.append(detail[0]);
				where.append("' and appId= '");
				if(StringUtils.isBlank(appId)){
					where.append(tCommunity.getAppId());
				}else{
					where.append(appId);
				}
				where.append("'");

				tuser = getByWhere(where.toString());
				if (tuser != null) {
					//名字为空就更新
					changeUser(tuser, detail[1]);
					//添加到申请钥匙list
					tUsers.add(tuser);
					//是否需要插入用户社区关系表
					if (StringUtils.isNotBlank(prvId)) {
						TLock tLock = tlocksService.get(Long.parseLong(prvId.split(",")[0]));
						updateUsersCommunity(communityId,Long.parseLong(tLock.getInstallunitId()),tuser.getUserId());
					}else{
						updateUsersCommunity(communityId,0L,tuser.getUserId());
					}
					continue;
				}
				tuser = new TUsers();
				tuser.setTel(detail[0]);
				tuser.setAuName(detail[1]);
				tuser.setNickName(detail[0].substring(detail[0].length()-4,detail[0].length()));
				tuser.setAgtCode(agtCode);
				if(StringUtils.isBlank(appId)){
					tuser.setAppId(tCommunity.getAppId());
				}else{
					tuser.setAppId(appId);
				}
				tuser.setAuTel(detail[0]);
				tuser.setcTime(new Timestamp(System.currentTimeMillis()));
				tuser.setcUserName(Long.toString(user.getSid()));
				String userId =  getUserID();
				tuser.setUserId(userId);
				tuser = add(tuser);
				//添加到申请钥匙list
				tUsers.add(tuser);
				//插入用户社区关系表
				if (StringUtils.isNotBlank(prvId)) {
					TLock tLock = tlocksService.get(Long.parseLong(prvId.split(",")[0]));
					updateUsersCommunity(communityId,Long.parseLong(tLock.getInstallunitId()),tuser.getUserId());
				}else{
					updateUsersCommunity(communityId,0L,tuser.getUserId());
				}
			}
			//查询pid
			result = lockList(pubId,prvId);
			if ("0".equals(result.get("code").toString())) {
				 return result;
			}
			List<TLock> list = (List<TLock>) result.get("lockList");
			List<String> pidList=new ArrayList<>();
			for(TLock lock:list){
				pidList.add(lock.getPid());
			}

			//调用接口查询钥匙
		    for (int i = 0; i < tUsers.size(); i++) {
		    	//result = tKeysService.SyncTo(tUsers.get(i), list,validityDate,agtCode,startTime);
		    	result=tKeysService.syncTo(tUsers.get(i).getUserId(), tUsers.get(i).getTel(), pidList, validityDate, agtCode, validityDate, startTime);//TODO wangk 2017-7-26 21:05:14
		    	if ("1".equals(result.get("code").toString())) {
		    		try {
						MdOpenBaseJson json = MdOpenApi.sendMsg(tUsers.get(i).getUserId(),null,"user","key_1");
		    		} catch (Exception e) {
		    			 log.error("推送消息失败",e);
		    		}
				}
			}

		} catch (Exception e) {
			log.error(this, e);
			 result.put("code", 0);
             result.put("msg", "预发钥匙为空！");
		}
		return result;
	}

/*	public Map<String, Object> authorizeKeysMethod(String data, String pubId, String prvId, String validityDate,String communityId, String agtCode, String appId,Date startTime) {
		try {
			//保存用户
			if (StringUtils.isBlank(data)) {
				 result.put("code", 0);
	             result.put("msg", "所选人员为空！");
	             return result;
			}
			String[] users = data.split(",");
			TUsers tuser;
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			//TCommunity tCommunity = tCommunityService.get(Long.parseLong(communityId));
			TCommunity tCommunity = (TCommunity)dao.getById(TCommunity.class,Long.parseLong(communityId));
			List<TUsers> tUsers = new ArrayList<TUsers>();
			Boolean bool = true;
			for(int i = 0; i < users.length; i++){
				String[] detail = users[i].split(";");
				String regex = "^1[3|4|5|7|8]\\d{9}$";
				if(!Pattern.matches(regex, detail[0])){
					bool = false;
				}
			}
			if(!bool){
				 result.put("code", 0);
	             result.put("msg", "预发用户中手机号格式不正确");
	             return result;
			}
			for (int i = 0; i < users.length; i++) {
				String[] detail = users[i].split(";");
				StringBuffer where  = new StringBuffer();
				where.append(" tel= '");
				where.append(detail[0]);
				where.append("' and appId= '");
				if(StringUtils.isBlank(appId)){
					where.append(tCommunity.getAppId());
				}else{
					where.append(appId);
				}
				where.append("'");

				tuser = getByWhere(where.toString());
				if (tuser != null) {
					//名字为空就更新
					changeUser(tuser, detail[1]);
					//添加到申请钥匙list
					tUsers.add(tuser);
					//是否需要插入用户社区关系表
					if (StringUtils.isNotBlank(prvId)) {
						TLock tLock = tlocksService.get(Long.parseLong(prvId.split(",")[0]));
						updateUsersCommunity(communityId,Long.parseLong(tLock.getInstallunitId()),tuser.getUserId());
					}else{
						updateUsersCommunity(communityId,0L,tuser.getUserId());
					}
					continue;
				}
				tuser = new TUsers();
				tuser.setTel(detail[0]);
				tuser.setAuName(detail[1]);
				tuser.setNickName(detail[0].substring(detail[0].length()-4,detail[0].length()));
				tuser.setAgtCode(agtCode);
				if(StringUtils.isBlank(appId)){
					tuser.setAppId(tCommunity.getAppId());
				}else{
					tuser.setAppId(appId);
				}
				tuser.setAuTel(detail[0]);
				tuser.setcTime(new Timestamp(System.currentTimeMillis()));
				tuser.setcUserName(Long.toString(user.getSid()));
				String userId =  getUserID();
				tuser.setUserId(userId);
				tuser = add(tuser);
				//添加到申请钥匙list
				tUsers.add(tuser);
				//插入用户社区关系表
				if (StringUtils.isNotBlank(prvId)) {
					TLock tLock = tlocksService.get(Long.parseLong(prvId.split(",")[0]));
					updateUsersCommunity(communityId,Long.parseLong(tLock.getInstallunitId()),tuser.getUserId());
				}else{
					updateUsersCommunity(communityId,0L,tuser.getUserId());
				}
			}
			//查询pid
			result = lockList(pubId,prvId);
			if ("0".equals(result.get("code").toString())) {
				 return result;
			}
			List<TLock> list = (List<TLock>) result.get("lockList");
			//调用接口查询钥匙
		    for (int i = 0; i < tUsers.size(); i++) {
		    	result = tKeysService.SyncTo(tUsers.get(i), list,validityDate,agtCode,startTime);
		    	if ("1".equals(result.get("code").toString())) {
		    		try {
						MdOpenBaseJson json = MdOpenApi.sendMsg(tUsers.get(i).getUserId(),null,"user","key_1");
		    		} catch (Exception e) {
		    			 log.error("推送消息失败",e);
		    		}
				}
			}

		} catch (Exception e) {
			log.error(this, e);
			 result.put("code", 0);
             result.put("msg", "预发钥匙为空！");
		}
		return result;
	}*/

	public String getUserID() {
		String userId = "";
		for (int i = 0; i < 10; i++) {
			userId = Long.toString(System.currentTimeMillis());
			userId += (int) ((Math.random() * 9 + 1) * 10000);
			String where ="userId= '"+userId+"'";
			TUsers tuer = getByWhere(where);
			if (tuer != null) {
				continue;
			}else{
				break;
			}
		}
		return userId;
	}

	@Override
	public Map<String, Object> userDetailQuery(String userId) {
		result = new HashMap<String, Object>();
		String where ="userId= '"+userId+"'";
		TUsers tUser = getByWhere(where);
		if (tUser == null) {
			result.put("code", 0);
            result.put("msg", "查询用户为空！");
            return result;
		}
		result.put("sid", tUser.getSid());
		result.put("userId", userId);
		if (StringUtils.isNotBlank(tUser.getAuName())) {
			result.put("name", tUser.getAuName());
		}else{
			result.put("name", "无");
		}
		if (StringUtils.isNotBlank(tUser.getTel())) {
			result.put("tel", tUser.getTel());
		}else{
			result.put("tel", "无");
		}
		if (StringUtils.isNotBlank(tUser.getNickName())) {
			result.put("nickName", tUser.getNickName());
		}else{
			result.put("nickName", "无");
		}
		if (StringUtils.isNotBlank(tUser.getSex())) {
			if ("0".equals(tUser.getSex())) {
				result.put("sex", "女");
			}else{
				result.put("sex", "男");
			}
		}else{
			result.put("sex", "无");
		}
		if (tUser.getcTime() != null) {
			result.put("ctime", DateUtils.formatDatetime(tUser.getcTime()));
		}else{
			result.put("ctime", "无");
		}
		//所属小区
		List<Map<String, String>> usersCommunitys =null;
		int userRole =  (Integer) getSession().getAttribute("userRole");
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		usersCommunitys = usersCommunityService.getByUserId(tUser.getUserId(),null,null);
    	}
    	if (userRole == 3 || userRole == 4) {
    		usersCommunitys = usersCommunityService.getByUserId(tUser.getUserId(),user.getAgtCode(),null);
    	}
    	if (userRole == 5 || userRole == 6) {
    		usersCommunitys = usersCommunityService.getByUserId(tUser.getUserId(),null,user.getCommunityId());
    	}

		if (usersCommunitys == null || usersCommunitys.size()<1) {
			result.put("comuNum", 0);
		}else{
			result.put("comuNum", usersCommunitys.size());
			StringBuffer sb = new StringBuffer();

			for (int i = 0; i < usersCommunitys.size(); i++) {
				if (sb.length() != 0) {
					sb.append(";");
				}
				sb.append(usersCommunitys.get(i).get("communityname"));
				sb.append(": ");
				sb.append(usersCommunitys.get(i).get("citycode"));
				sb.append(" / ");
				if (StringUtils.isNotBlank(usersCommunitys.get(i).get("street"))) {
					sb.append(usersCommunitys.get(i).get("street"));
					sb.append(" / ");
				}
				sb.append(usersCommunitys.get(i).get("communityname"));
				sb.append(" / ");
				if (StringUtils.isNotBlank(usersCommunitys.get(i).get("cbname"))) {
					sb.append(usersCommunitys.get(i).get("cbname"));
				}
				if (StringUtils.isNotBlank(usersCommunitys.get(i).get("installName"))) {
					sb.append(usersCommunitys.get(i).get("installName"));
				}
			}
			result.put("comu", sb.toString());
			result.put("code", 1);
		}
		//排名和信誉分
		List<Map<String, Object>> list = null;
		if (usersCommunitys.size()>1) {
			result.put("score", usersCommunitys.get(0).get("score"));
			result.put("rownu", "hidden");
		}else{
			String counId = String.valueOf(usersCommunitys.get(0).get("communityid"));
			list = usersEnjoyService.queryRownuScore(counId,userId);
			if (list.size() >0) {
				result.put("rownu", list.get(0).get("rownu"));
				result.put("score", list.get(0).get("score"));
			}else{
				result.put("rownu", 0);
				result.put("score", 0);
			}
		}

		return result;
	}

	 /**
     * 操作用户权限判断
     * @param tUser2
     * @return
     */
	@Override
	public boolean haveRole(String userId) {
		String where ="userId= '"+userId+"'";
		TUsers tUser = getByWhere(where);
		if (tUser ==null) {
			return false;
		}
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	if (userRole == 3 || userRole == 4) {
    		if(!user.getAgtCode().equals(tUser.getAgtCode())){
    			return false;
    		}
    	}
		if (userRole == 5 || userRole == 6) {
			if(!(user.getAgtCode().equals(tUser.getAgtCode()))){
    			return false;
    		}
			StringBuffer sb = new StringBuffer(" status=1 and communityId ='");
			sb.append(user.getCommunityId());
			sb.append("'");
			sb.append(" and userId='");
			sb.append(userId);
			sb.append("'");
			UsersCommunity usersCommunity = usersCommunityService.getByWhere(sb.toString());
			if(usersCommunity == null){
				return false;
			}
		}
		return true;
	}

	@Override
	public List<Map<String, String>> list(String sql) {
		return dao.queryBySql(sql);
	}

	@Override
	public Map<String, Object> addTestKeyMethod(String sid, String tel, String userName, String validity) {
		try {
			StringBuilder data = new StringBuilder();
			data.append(tel);
			data.append(";");
			data.append(userName);
			String pubId =sid;
			String prvId = "";
			if(StringUtils.isBlank(validity)){
				Calendar calendar = Calendar.getInstance();
				Date date = new Date(System.currentTimeMillis());
				calendar.setTime(date);
				calendar.add(Calendar.DATE, +3);//需求由1天改为3天 by  wangk 2017-6-1
				date = calendar.getTime();
				validity = DateUtils.dateFormat.format(date);
			}




			if(sid.indexOf(",")>-1){
				sid = sid.split(",")[0];
			}
			TLock entity = tlocksService.get(Long.parseLong(sid));
			StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
    		where.append(" and agtCode ='");
    		where.append(entity.getAgtCode());
    		where.append("'");
    		AppStore appStores = (AppStore) appStoreService.get(where.toString());
    		if(appStores==null){
    			result.put("code", "-1");
    			result.put("msg", "该未合作方还未指定APP,暂时无法发钥匙");
    			return result;
    		}
			//直接调用预发钥匙方法
			result = authorizeKeysMethod(data.toString(), pubId, prvId, DateUtils.stringToDate(validity,"yyyy-MM-dd"), entity.getCommunityId(), entity.getAgtCode(),appStores.getAppId(),null);

		} catch (Exception e) {
			log.error("钥匙申请失败", e);
    		result.put("code", 0);
  	        result.put("msg", "钥匙申请失败");
  	        throw new MdKnownRunTimeException("钥匙申请失败");
		}
		return result;
	}



	@Override
	public TUsers getOrCreatTuser(String communityId, String tel, String name, String unitId) {
		TUsers tuser = null;
		try {
			//TCommunity tCommunity = tCommunityService.get(Long.parseLong(communityId));
			TCommunity tCommunity = (TCommunity)dao.getById(TCommunity.class,Long.parseLong(communityId));
			StringBuffer where  = new StringBuffer();
			where.append(" tel= '");
			where.append(tel);
			where.append("' and appId= '");
			where.append(tCommunity.getAppId());
			where.append("'");

			tuser = getByWhere(where.toString());
			if (tuser != null) {
				//名字为空就更新
				changeUser(tuser, name);
				//是否需要插入用户社区关系表
				updateUsersCommunity(communityId,Long.parseLong(unitId),tuser.getUserId());
				return tuser;
			}
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			tuser = new TUsers();
			tuser.setTel(tel);
			tuser.setAuName(name);
			tuser.setNickName(tel.substring(tel.length()-4,tel.length()));
			tuser.setAgtCode(tCommunity.getAgtCode());
			tuser.setAppId(tCommunity.getAppId());
			tuser.setAuTel(tel);
			tuser.setcTime(new Timestamp(System.currentTimeMillis()));
			tuser.setcUserName(Long.toString(user.getSid()));
			String userId =  getUserID();
			tuser.setUserId(userId);
			tuser = add(tuser);
			updateUsersCommunity(communityId,Long.parseLong(unitId),tuser.getUserId());
		} catch (Exception e) {
			log.error("查找或者新增用户数失败", e);
  	        throw new MdKnownRunTimeException("查找或者新增用户数失败");
		}
		return tuser;
	}

	@Override
	public TUsers getByUserid(String userid) {

		String hql="from TUsers where userid= '"+userid+"'";
		try {
			return (TUsers)dao.getUniqueFirst(hql);
		} catch (NotUniqueException e) {
			log.error(this, e);
			return null;
		}
	}

	@Override
	public boolean checkUser4WebAuth(String appUserid, String token) {
		TUsers users = getByUserid(appUserid);
		if(users!=null&&MD5.MD5Encode(users.getToken()).toUpperCase().equals(token.toUpperCase())){
			return true;
		}
		return false;
	}
}
